package butines.core.math;

public class Geometry {

	public static float distToLineSegment(Vector2f a, Vector2f b, Vector2f p) {
		// if the angle is obtuse between PA and AB is obtuse then the closest vertex must be A
		float dotA = (p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y);

		if (dotA <= 0) {
			return Vector2f.distance(a, p);
		}

		//if the angle is obtuse between PB and AB is obtuse then the closest vertex must be B
		float dotB = (p.x - b.x) * (a.x - b.x) + (p.y - b.y) * (a.y - b.y);

		if (dotB <= 0) {
			return Vector2f.distance(b, p);
		}

		//calculate the point along AB that is the closest to P
		//A + ((B - A) * dotA)/(dotA + dotB)
		float x = a.x + (b.x - a.x) * dotA / (dotA + dotB);
		float y = a.y + (b.y - a.y) * dotA / (dotA + dotB);

		float dx = x - p.x;
		float dy = y - p.y;
		
		return (float)Math.sqrt(dx * dx + dy * dy);

	}
	
}
